package com.example.yls.wuziqi;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import static android.content.ContentValues.TAG;

/**
 * Created by yls on 2018/6/13.
 */

public class WuziqiaView extends View {
    private int mPanelWidth;
    private float mLineHeight;
    private int MAX_LINE=10;
    private static final int MAX_COUNT_IN_LINE =5 ;

    private Paint mPaint=new Paint();

    private Bitmap mWhitePiece;
    private Bitmap mBlackPiece;

    private float reatioPieceOfLineHeight = 3*1.0f/4;

    //白棋先手，当前轮到白棋
    private boolean mIsWhite = true;
    private ArrayList<Point> mWhiteArray = new ArrayList<>();
    private ArrayList<Point> mBlackArray = new ArrayList<>();

    private boolean mIsGemeoVer;
    private  boolean mIsWhiteWinner;

    public WuziqiaView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        setBackgroundColor(0x44ff0000);
        init();
    }

    private void init() {
        mPaint.setColor(0x88000000);
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setStyle(Paint.Style.STROKE);

        mWhitePiece = BitmapFactory.decodeResource(getResources(),R.drawable.stone_w2);
        mBlackPiece = BitmapFactory.decodeResource(getResources(),R.drawable.stone_b1);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        /***
         * 这个模式分为三种
         * AT_MOST（这个子控件可以制定大小，常量值是-2147483648）
         * EXACTLY （这个子控件根据父类进行调整，最大就是父类的大小，常量值是1073741824）
         * UNSPECIFIED （这个子控件是任意大小与父类无关，常量值是0）
         */

        Log.i(TAG, "widthSize—" + widthSize);
        Log.i(TAG, "widthMode—" + widthMode);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        Log.i(TAG, "heightSize—" + heightSize);
        Log.i(TAG, "heightMode—" + heightMode);
        int width = Math.min(widthSize, heightSize);
        Log.i(TAG, "—" + width);
        /*
     分辨率：
     widthSize—1080
     widthMode—1073741824   可以确定下来是子空间最大是父类布局的大小
     heightSize—1920
     heightMode—1073741824
     —1080*/
        Log.i(TAG, "" + MeasureSpec.UNSPECIFIED);
        Log.i(TAG, "" + MeasureSpec.AT_MOST);
        Log.i(TAG, "" + MeasureSpec.EXACTLY);
        if (widthMode == MeasureSpec.UNSPECIFIED) {
            width = heightSize;
            Log.i(TAG, "我不会被运行到1");
        } else if (heightMode == MeasureSpec.UNSPECIFIED) {
            width = widthSize;
            Log.i(TAG, "我不会被运行到2");
        }
        setMeasuredDimension(width, width);//设置子控件的大小 该方法必须要在onMeasure调用
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        Log.i(TAG, "w" + w);//1080
        mPanelWidth = w;
        mLineHeight = mPanelWidth * 1.0f / MAX_LINE;
        //确定行高宽  将整个控件的宽平均分成10份，得出一份的宽度，因为是正方形所以也是高度 1080.0/10 = 108.0

        //改变棋子的尺寸
        int pieceWidth = (int) (mLineHeight*reatioPieceOfLineHeight);
        //确定棋子的高款为一个单位的高度宽度的3/4 108.0*3/4 = 81.0  
        mWhitePiece = Bitmap.createScaledBitmap(mWhitePiece,pieceWidth,pieceWidth,false);
        mBlackPiece = Bitmap.createScaledBitmap(mBlackPiece,pieceWidth,pieceWidth,false);

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mIsGemeoVer) return false;//如果游戏结束，不能再次下子。
        int action = event.getAction();
        if (action == MotionEvent.ACTION_UP) {
            int x = (int) event.getX();
            int y = (int) event.getY();
            //Point point = new Point(x, y);//确定的点
            Point point = getValidPoint(x, y);//不能重复下 ，不能下到一个点，不能仅仅根据坐标进行下棋所以有合理的点
            if (mWhiteArray.contains(point) || mBlackArray.contains(point)) {
                return false;
            }
            if (mIsWhite) {
                mWhiteArray.add(point);
            } else {
                mBlackArray.add(point);
            }
            invalidate();//刷新View
            mIsWhite = !mIsWhite;//改变值
            return true;
        }
        return true;
    }

    private Point getValidPoint(int x, int y) {
        return new Point((int)(x/mLineHeight),(int)(y/mLineHeight));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawBoard(canvas);
        drawPieces(canvas);
        checkGameOver();
    }
    /***
     * 游戏胜利主监听
     */
    private void checkGameOver() {
        boolean whiteWin = checkFiveInLine(mWhiteArray);
        boolean blackWin = checkFiveInLine(mBlackArray);
        if (whiteWin || blackWin) {
            mIsGemeoVer = true;
            mIsWhiteWinner = whiteWin;
            String text = mIsWhiteWinner ? "白棋胜利" : "黑棋胜利";
            Toast.makeText(getContext(), text, Toast.LENGTH_SHORT).show();
        }
    }

    private boolean checkFiveInLine(List<Point> points) {
        for(Point p :points){
            int x = p.x;
            int y = p.y;

            boolean win =checkWinHorizontal(x,y,points);
            if(win)return true;
           win =checkWinVertical(x,y,points);
            if(win)return true;
           win =checkLeftDiagonal(x,y,points);
            if(win)return true;
            win =checkRightDiagonal(x,y,points);
            if(win)return true;
        }
        return false;
    }

    //横着
    private boolean checkWinHorizontal(int x, int y, List<Point> points) {
        //横着左
        int count = 1;
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (points.contains(new Point(x - i, y))) {
                count++;
            } else {
                break;
            }
        }
        if (count == MAX_COUNT_IN_LINE) return true;

        //横着右
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (points.contains(new Point(x + i, y))) {
                count++;
            } else {
                break;
            }
        }
        if (count == MAX_COUNT_IN_LINE) return true;
        return false;
    }

    //竖着
    private boolean checkWinVertical(int x, int y, List<Point> points) {
        //竖着上
        int count = 1;
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (points.contains(new Point(x, y-i))) {
                count++;
            } else {
                break;
            }
        }
        if (count == MAX_COUNT_IN_LINE) return true;

        //竖着下
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (points.contains(new Point(x, y+i))) {
                count++;
            } else {
                break;
            }
        }
        if (count == MAX_COUNT_IN_LINE) return true;
        return false;
    }
    //左斜
    private boolean checkLeftDiagonal(int x, int y, List<Point> points) {
        //左斜上
        int count = 1;
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (points.contains(new Point(x-i, y-i))) {
                count++;
            } else {
                break;
            }
        }
        if (count == MAX_COUNT_IN_LINE) return true;

        //左斜下
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (points.contains(new Point(x+i, y+i))) {
                count++;
            } else {
                break;
            }
        }
        if (count == MAX_COUNT_IN_LINE) return true;
        return false;
    }

    //右斜
    private boolean checkRightDiagonal(int x, int y, List<Point> points) {
        //右斜上
        int count = 1;
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (points.contains(new Point(x+i, y-i))) {
                count++;
            } else {
                break;
            }
        }
        if (count == MAX_COUNT_IN_LINE) return true;

        //右斜下
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (points.contains(new Point(x-i, y+i))) {
                count++;
            } else {
                break;
            }
        }
        if (count == MAX_COUNT_IN_LINE) return true;
        return false;
    }

    private void drawPieces(Canvas canvas) {
        for (int i = 0, n = mWhiteArray.size(); i < n; i++) {
            Point whitePoint = mWhiteArray.get(i);
            Log.i(TAG, "whitePoint" + whitePoint);
            //drawBitmap(Bitmap bitmap, float left, float top, Paint paint)
            canvas.drawBitmap(mWhitePiece, (whitePoint.x + (1 - reatioPieceOfLineHeight) / 2) * mLineHeight,//  3.0/4  -->  1.0/4  -->  1.0/8 -->
                    (whitePoint.y + (1 - reatioPieceOfLineHeight) / 2) * mLineHeight, null);
        }

        for (int i = 0, n = mBlackArray.size(); i < n; i++) {
            Point blackPoint = mBlackArray.get(i);
            //drawBitmap(Bitmap bitmap, float left, float top, Paint paint)
            canvas.drawBitmap(mBlackPiece, (blackPoint.x + (1 - reatioPieceOfLineHeight) / 2) * mLineHeight,//  3.0/4  -->  1.0/4  -->  1.0/8 -->
                    (blackPoint.y + (1 - reatioPieceOfLineHeight) / 2) * mLineHeight, null);
        }
    }



    private void drawBoard(Canvas canvas) {
        int w = mPanelWidth;
        float lineHeight = mLineHeight;
        for (int i = 0; i <MAX_LINE ; i++) {
            int startX = (int) (lineHeight/2);
            int endX = (int) (w-lineHeight/2);
            int y = (int) ((0.5+i)*lineHeight);
            canvas.drawLine(startX,y,endX,y,mPaint);
            canvas.drawLine(y,startX,y,endX,mPaint);
        }
    }
    /***
     * 防止View配置改变被杀死处理
     */
    private static final String INSTANCE = "instance";
    private static final String INSTANCE_GAME_OVER = "instance_game_over";
    private static final String INSTANCE_WHITE_ARRAY = "instance_white_array";
    private static final String INSTANCE_BLACK_ARRAY = "instance_black_array";

    @Override
    protected Parcelable onSaveInstanceState() {
        Bundle bundle = new Bundle();
        bundle.putParcelable(INSTANCE, super.onSaveInstanceState());

        bundle.putBoolean(INSTANCE_GAME_OVER, mIsGemeoVer);
        bundle.putParcelableArrayList(INSTANCE_WHITE_ARRAY, mWhiteArray);
        bundle.putParcelableArrayList(INSTANCE_BLACK_ARRAY, mBlackArray);

        return bundle;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        if (state instanceof Bundle) {
            Bundle bundle = (Bundle) state;

            mIsGemeoVer = bundle.getBoolean(INSTANCE_GAME_OVER);
            mWhiteArray = bundle.getParcelableArrayList(INSTANCE_WHITE_ARRAY);
            mBlackArray = bundle.getParcelableArrayList(INSTANCE_BLACK_ARRAY);

            super.onRestoreInstanceState(bundle.getParcelable(INSTANCE));
            return;
        }
        super.onRestoreInstanceState(state);
    }

    //再来一局
    public void agin() {
        mWhiteArray.clear();
        mBlackArray.clear();
        mIsGemeoVer = false;
        mIsWhiteWinner = false;
        invalidate();
    }

}
